﻿using Api.Shared.Model.Web.Login;
using Api.Shared.Sugar;
using Api.Shared.Utils;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace FitterTest.Controllers
{
    [Route("api/private/v1/[controller]/[action]")]
    [ApiController]
    [EnableCors("any")]
    public class UsersController : ControllerBase
    {
        private readonly ISugarClientService helper;
        private readonly MySession mySession;

        public UsersController([FromKeyedServices(nameof(SqlName.sqlite))] ISugarClientService helper, MySession mySession)
        {
            this.helper = helper;
            this.mySession = mySession;
        }
        /// <summary>
        /// 总查询
        /// </summary>
        /// <param name="queryInfo">查询参数</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Users([FromQuery] QueryInfo queryInfo)
        {
            if (queryInfo.Pagenum <= 0)
            {
                return StatusCode(204, "Failed");
            }
            if (queryInfo.Pagesize <= 0)
            {
                return StatusCode(204, "Failed");
            }
            int totalNumber = 0;

            var exp = Expressionable.Create<User>();
            exp.AndIF(!string.IsNullOrWhiteSpace(queryInfo.Query), x => x.UserName != null && x.UserName.Contains(queryInfo.Query!));

            exp.AndIF(queryInfo.DateStart != null, x => x.CreateTime > queryInfo.DateStart);

            exp.AndIF(queryInfo.DateEnd != null, x => x.CreateTime < queryInfo.DateEnd);

            exp.AndIF(queryInfo.DateEnd != null && queryInfo.DateStart != null, x => (x.CreateTime < queryInfo.DateEnd && x.CreateTime > queryInfo.DateStart));

            //exp.AndIF  第一个条件为真，才计算第二个表达式 ,exp.OR 第一个条件为假，才计算第二个表达式  
            var users = this.helper.Db.Queryable<User>()
                .Where(exp.ToExpression())
                .ToPageList(queryInfo.Pagenum, queryInfo.Pagesize, ref totalNumber);


            //int maxPageCount = (int)Math.Ceiling((double)totalNumber / queryInfo.Pagesize);
            var resultData = new
            {
                total = totalNumber,
                pagenum = queryInfo.Pagenum,
                users = users
            };
            if (users.Count > 0)
            {
                return Ok(resultData);
            }
            else
            {
                return StatusCode(204, "Failed");
            }
        }

        /// <summary>
        /// toggleBtn的状态
        /// </summary>
        /// <param name="userId">用户id</param>
        /// <param name="mgState">toggleBtn的状态</param>
        /// <returns></returns>
        [HttpPut("{userId}/state/{mgState}")]
        public IActionResult UpdateUserState(string userId, string mgState)
        {
            User user = this.helper.Db.Queryable<User>().InSingle(int.Parse(userId));
            user.MgState = bool.Parse(mgState);
            int count = this.helper.Db.Updateable<User>(user).ExecuteCommand();
            if (count > 0)
            {
                return Ok();
            }
            else
            {
                return StatusCode(204, "Failed");
            }
        }

        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="user">新增User对象</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddUser([FromBody] User user)
        {
            //不能访问到后端，class的字段类型后置为空
            if (string.IsNullOrEmpty(user.UserSex))
            {
                user.UserSex = "男";
                user.UserQq = "123456";
                user.UserTel = "1212121";
                user.UserHobby = "ddddd";
                user.CreateTime = DateTime.Now;
                user.UpdateTime = DateTime.Now;
                user.RoleName = "测试员";
            }
            int count = this.helper.Db.Insertable<User>(user).ExecuteCommand();
            //int count = 1;
            if (count > 0)
            {
                return Ok();
            }
            else
            {
                return StatusCode(204, "Failed");
            }
        }

        [HttpGet("{userId}")]
        public async Task<IActionResult> GetUserById(string userId)
        {
            User user = await this.helper.Db.Queryable<User>().InSingleAsync(int.Parse(userId));
            if (user != null)
            {
                return Ok(user);
            }
            else
            {
                return StatusCode(204, "Failed");
            }
        }
        /// <summary>
        /// 根据id修改，返回id和Body
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="user">用户实体</param>
        /// <returns></returns>
        [HttpPut("{userId}")]
        public async Task<IActionResult> UpdateUserByIdAndModel(string userId, [FromBody] User user)
        {
            if (int.Parse(userId) == user.UserId)
            {
                int count = await this.helper.Db.Updateable<User>(user).ExecuteCommandAsync();
                if (count > 0)
                {
                    return Ok();
                }
                return StatusCode(204, "Failed");
            }
            else
            {
                return StatusCode(204, "Failed");
            }
        }

        /// <summary>
        /// 单个删除
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpDelete("{userId}")]
        public IActionResult DeleteUserById(string userId)
        {
            int count = this.helper.Db.Deleteable<User>().In(int.Parse(userId)).ExecuteCommand();
            if (count > 0)
            {
                return Ok();
            }
            else
            {
                return StatusCode(204, "Failed");
            }

        }

        [HttpPut("{UserId}/role/{Rid}")]
        public IActionResult ChangeRoleId([FromRoute] int UserId, [FromRoute] int Rid)
        {
            if (UserId <= 0 | Rid <= 0)
            {
                return StatusCode(204, "返回UserId 或 Rid为空");
            }
            User user = helper.Db.Queryable<User>().Where(x => x.UserId == UserId).First();
            if (user.RoleName == "超级管理员")
            {
                return StatusCode(204, "超级管理员不能被修改");
            }

            user.UpdateTime = DateTime.Now;

            user.RoleName = mySession.RoleUsers[Rid];

            int t = this.helper.Db.Updateable<User>(user).ExecuteCommand();
            if (t <= 0)
            {
                return StatusCode(204, "数据库修改失败");
            }
            return Ok();
        }

    }
}
